package com.school.fuyuan.common.aspect;

import com.school.fuyuan.common.message.RequestHead;
import com.school.fuyuan.common.message.RequestMsg;
import com.school.fuyuan.common.message.ResponseHead;
import com.school.fuyuan.common.message.ResponseMsg;
import com.school.fuyuan.common.util.JsonUtils;
import com.school.fuyuan.common.util.ParameterUtils;
import com.school.fuyuan.common.util.RequestUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author zrhong
 * @version 1.0
 * @date 2019/3/3 20:42
 * @description
 */
@Aspect
@Component
public class WebLogAspect {

    private static final ThreadLocal<Long> START_TIME_THREAD_LOCAL = new ThreadLocal<>();
    private static final ThreadLocal<Map<String, Object>> REQUEST_MAP_THREAD_LOCAL = new ThreadLocal<>();

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    // 两个..代表所有子目录，最后括号里的两个..代表所有参数
    @Pointcut("execution(public * com.school.fuyuan.business.controller.*.*(..))")
    public void logPointCut() {}

    @Before("logPointCut()")
    public void doBefore(JoinPoint joinPoint) {

        START_TIME_THREAD_LOCAL.set(System.currentTimeMillis());

        // 接收到请求，记录请求内容
        HttpServletRequest request = RequestUtils.getRequest();
        Signature signature = joinPoint.getSignature();

        String url = request.getRequestURL().toString();
        String remoteAddr = request.getRemoteAddr();
        String httpMethod = request.getMethod();
        String classMethod = signature.getDeclaringTypeName() + "." + signature.getName();

        Map<String, Object> requestMap = new LinkedHashMap<>();
        requestMap.put("remoteAddr", remoteAddr);
        requestMap.put("url", url);
        requestMap.put("httpMethod", httpMethod);
        requestMap.put("classMethod", classMethod);

        Object[] args = joinPoint.getArgs();
        if (ParameterUtils.isEmpty(args)) {
            args = new Object[]{"no parameter，无入参"};
        }

        Object firstArg = args[0];

        if (firstArg instanceof RequestMsg) {
            requestMap.put("requestData", ((RequestMsg) firstArg).getData());
            requestMap.put("requestHead", ((RequestMsg) firstArg).getHead());
        } else {
            Object[] clone = args.clone();
            for (int i = 0; i < clone.length; i++) {
                Object o = clone[i];
                if (o instanceof ServletRequest
                        || o instanceof ServletResponse
                        || o instanceof HttpSession) {
                    clone[i] = o.toString();//防止JsonUtils.toJsonStr操作报错
                }
            }
            requestMap.put("data", clone);
        }

        if (logger.isErrorEnabled()) {
            logger.error("request : {} ", JsonUtils.toJsonStr(requestMap));
        }

        REQUEST_MAP_THREAD_LOCAL.set(requestMap);
    }

    @AfterReturning(returning = "ret", pointcut = "logPointCut()")
    // returning的值和doAfterReturning的参数名一致
    public void doAfterReturning(Object ret) {

        Map<String, Object> requestMap = REQUEST_MAP_THREAD_LOCAL.get();
        if (ret instanceof ResponseMsg) {
            ResponseHead head = ((ResponseMsg) ret).getHead();
            RequestHead requestHead = (RequestHead) requestMap.get("requestHead");
            requestMap.put("responseHead", head);
            requestMap.put("responseData", ((ResponseMsg) ret).getData());
        }

        long costTime = System.currentTimeMillis() - START_TIME_THREAD_LOCAL.get();
        requestMap.put("costTime", costTime);   //处理日志

        // 处理完请求，返回内容
        if (logger.isErrorEnabled()) {
            logger.error("response : {} ", JsonUtils.toJsonStr(requestMap));
        }

        START_TIME_THREAD_LOCAL.remove();
        REQUEST_MAP_THREAD_LOCAL.remove();
    }

    @AfterThrowing(value = "logPointCut()", throwing = "ex")
    public void doAfterThrowing(Exception ex) {

        HttpServletRequest request = RequestUtils.getRequest();

        Map<String, Object> requestMap = REQUEST_MAP_THREAD_LOCAL.get();
        if (!ParameterUtils.isEmpty(requestMap)) {
            Object requestHead = requestMap.get("requestHead");
            if (requestHead instanceof RequestHead) {
                request.setAttribute("requestId", ((RequestHead) requestHead).getRequestId());
            }
        }
        request.setAttribute("requestMap", requestMap);
        request.setAttribute("startTime", START_TIME_THREAD_LOCAL.get());

        START_TIME_THREAD_LOCAL.remove();
        REQUEST_MAP_THREAD_LOCAL.remove();
    }
}
